import { ref, onMounted } from "vue";
import { getBannerAPI } from "@/apis/home";
import { getTopCategoryAPI } from "@/apis/category";
import { useRoute, onBeforeRouteUpdate } from "vue-router";

const route = useRoute();

// 1. 获取分类轮播图数据
export const useBanner = () => {
  const bannerList = ref([]);
  const getBannerList = async () => {
    const res = await getBannerAPI(2);
    bannerList.value = res.result;
  };
  onMounted(() => {
    getBannerList();
  });

  return { bannerList }
}

// 2. 获取分类所有数据
export const useCategory = () => {
  const route = useRoute();
  const category = ref({});
  const getCategory = async (id) => {
    // console.log(route.params.id);
    const res = await getTopCategoryAPI(id);
    console.log(res);
    category.value = res.result;
  };
  onMounted(() => {
    getCategory(route.params.id);
  });
  onBeforeRouteUpdate((to) => {
    console.log("地址栏中的地址发生变化", to.params.id);
    // 重新获取分类数据
    getCategory(to.params.id);
  });

  return {
    category
  }
}